package com.epoint.mobileoa.ui.init;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.epoint.mobileoa.R;
import com.epoint.mobileoa.bizlogic.ConfigKey;
import com.epoint.mobileoa.db.DBHelp;
import com.epoint.mobileoa.tools.AlertHelp;
import com.epoint.mobileoa.tools.IOHelp;
import com.epoint.mobileoa.tools.LogHelp;
import com.epoint.mobileoa.tools.MDUtil;
import com.epoint.mobileoa.tools.PhoneHelp;
import com.epoint.mobileoa.tools.PropertiesHelp;
import com.epoint.mobileoa.tools.ToastHelp;
import com.epoint.mobileoa.ui.login.LoginView;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Window;
import android.widget.EditText;
import android.widget.LinearLayout;

/**
 * @author liyc
 * @time 2011-12-28 下午6:29:50
 * @annotation 初始化页，串码注册
 */
public class InitView extends Activity{

	private String backup_db = "mobileoa_backup_db.mp3";
	private String main_folder;
	private String keyname = "epoint_mobileoa.lic";

	//主存储目录
	public static String MobileOaMainStoreFolder = "sdcard";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.init);

		//取配置文件主存储目录
		main_folder = "/"+MobileOaMainStoreFolder+"/"+getString(R.string.sdforder);

		if(MobileOaMainStoreFolder.equals("sdcard")){
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				check();
			}else { 
				AlertHelp.ShowAlertSingleButton(this, "请检查当前SD卡是否可用？", new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						finish();
					}
				});
			}  
		}
		else{
			check();
		}
	}

	//获取IP
	public String getTempKey(){
		String ipStr;
		try{
			ipStr = IOHelp.readtxt(InitView.MobileOaMainStoreFolder+"/"+getString(R.string.sdforder)+"/"+"tmp");
		}catch(Exception e){
			ipStr = "";
		}
		return ipStr;
	}

	public void check(){
		
		if(PropertiesHelp.getProperty(this, "initWithKey").equals("1")){

			IOHelp.FoldCreate(main_folder);

			String key = IOHelp.readtxt(main_folder+"/"+keyname);

			final String temp = MDUtil.jm2Md(PhoneHelp.getDeviceId(this));

			if(key.contains(temp)){
				init();
			}
			else{
				AlertDialog.Builder ab = new AlertDialog.Builder(this)
				.setIcon(R.drawable.epoint2)
				.setTitle("新点软件")
				.setMessage("无使用授权！\n\n设备ID："+PhoneHelp.getDeviceId(this))
				.setPositiveButton("输入授权码", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						final String tmpkeyinputpath = "/"+InitView.MobileOaMainStoreFolder+"/"+getString(R.string.sdforder)+"/"+"tmp";
						LayoutInflater inflater2 = LayoutInflater.from(InitView.this);
						LinearLayout ll = (LinearLayout) inflater2.inflate(R.layout.alertinput_editview, null);
						final EditText et = (EditText) ll.findViewById(R.id.ai_et);
						et.setText(IOHelp.readtxt(tmpkeyinputpath));
						AlertDialog.Builder inputab = new AlertDialog.Builder(InitView.this)
						.setIcon(R.drawable.epoint2)
						.setTitle("请输入授权码")
						.setView(ll)
						.setPositiveButton("验证", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {
								String inputKey = et.getText().toString().toUpperCase();
								if(inputKey.contains(temp)){
									ToastHelp.showToast(InitView.this, "授权码验证成功");
									IOHelp.writeText2Path("/"+InitView.MobileOaMainStoreFolder+"/"+getString(R.string.sdforder)+"/"+keyname, inputKey);
									init();
								}
								else{
									DBHelp.setConfigValue(InitView.this, ConfigKey.epointLicKey, inputKey);
									ToastHelp.showToast(InitView.this, "授权码无效");
									AlertHelp.notHide(dialog);
								}
								IOHelp.writeText2Path(tmpkeyinputpath, inputKey);
							}
						})
						.setNegativeButton("取消", new OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								finish();
							}
						});
						inputab.create().show();
					}
				})
				.setNegativeButton("退出", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						finish();
					}
				});
				ab.create().show();
			}
		}
		else{
			init();
		}
	}

	public void init(){
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				loadData();
			}
		},1500);
	}

	public void loadData(){
		boolean exist = DBHelp.exist(this);
		if(exist){
			LogHelp.LogI("数据库存在！");
		}
		else{
			try {
				File dbfolder = new File(getString(R.string.dbpath));
				if(!dbfolder.exists()){
					dbfolder.mkdirs();
				}
				InputStream fis = getResources().getAssets().open(backup_db);
				FileOutputStream fos = new FileOutputStream(getString(R.string.dbpath)+getString(R.string.dbname));
				byte data[] = new byte[1024];
				int count;
				while ((count = fis.read(data)) != -1) {
					fos.write(data, 0, count);
				}
				fos.flush();
				fos.close();
				fis.close();
			} catch (IOException e) {
			}
		}
		Intent intent = new Intent(InitView.this,LoginView.class);
		startActivity(intent);
		finish();
	}
}
